#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
from typing import Dict, Any, Optional, List
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Settings:
    """应用程序配置"""
    
    def __init__(self):
        # 应用程序配置
        self.APP_NAME = "Text2SQL RAG API"
        self.APP_VERSION = "0.1.0"
        self.APP_DESCRIPTION = "Text-to-SQL system using RAG approach"
        self.DEBUG = os.getenv("DEBUG", "False").lower() == "true"
        
        # API配置
        self.API_PREFIX = "/api/v1"
        
        # 数据库配置
        self.MYSQL_HOST = os.getenv("MYSQL_HOST")
        self.MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
        self.MYSQL_USER = os.getenv("MYSQL_USER")
        self.MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD")
        self.MYSQL_DB = os.getenv("MYSQL_DB")
        self.MYSQL_POOL_SIZE = int(os.getenv("MYSQL_POOL_SIZE", "5"))
        self.MYSQL_POOL_RECYCLE = int(os.getenv("MYSQL_POOL_RECYCLE", "3600"))
        
        # Milvus配置
        self.MILVUS_HOST = os.getenv("MILVUS_HOST")
        self.MILVUS_PORT = int(os.getenv("MILVUS_PORT", "19530"))
        self.MILVUS_USER = os.getenv("MILVUS_USER")
        self.MILVUS_PASSWORD = os.getenv("MILVUS_PASSWORD")
        
        # LiteLLM配置
        self.LITELLM_API_KEY = os.getenv("LITELLM_API_KEY")
        self.LITELLM_MODEL = os.getenv("LITELLM_MODEL", "gpt-3.5-turbo")
        self.LITELLM_TEMPERATURE = float(os.getenv("LITELLM_TEMPERATURE", "0.0"))
        self.LITELLM_MAX_TOKENS = int(os.getenv("LITELLM_MAX_TOKENS", "1024"))
        
        # 向量嵌入配置
        self.EMBEDDING_PROVIDER = os.getenv("EMBEDDING_PROVIDER", "ollama")
        self.EMBEDDING_DIMENSION = int(os.getenv("EMBEDDING_DIMENSION", "1536"))
        self.ALIBABA_EMBEDDING_MODEL = os.getenv("ALIBABA_EMBEDDING_MODEL", "text-embedding-v1")
        self.ALIBABA_API_KEY = os.getenv("ALIBABA_API_KEY")
        
        # 获取 Ollama 服务 URL
        self.OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL")
        if not self.OLLAMA_BASE_URL:
            # 使用默认值
            self.OLLAMA_BASE_URL = "http://10.133.4.16:11434"
            print(f"警告: OLLAMA_BASE_URL 环境变量未设置，使用默认值: {self.OLLAMA_BASE_URL}")
        else:
            print(f"信息: 使用 OLLAMA_BASE_URL: {self.OLLAMA_BASE_URL}")
            
        # 设置环境变量，确保其他库也能使用
        os.environ["OLLAMA_API_BASE"] = self.OLLAMA_BASE_URL
        
        self.OLLAMA_EMBEDDING_MODEL = os.getenv("OLLAMA_EMBEDDING_MODEL", "llama2")
        
        # 日志配置
        self.LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
        
        # 验证必要的配置
        self._validate()
    
    def _validate(self):
        """验证配置"""
        if not self.MYSQL_DB:
            raise ValueError("数据库名称不能为空")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
    
    def __str__(self) -> str:
        """字符串表示"""
        return json.dumps(self.to_dict(), indent=2, ensure_ascii=False)


# 创建全局设置实例
settings = Settings()